package com.zheng.redpacket.server.utils.publisher;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zheng.redpacket.server.dto.UserLoginDto;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.AbstractJavaTypeMapper;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class LoginPublisher {
    private static final Logger LOGGER = LoggerFactory.getLogger(LoginPublisher.class);
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private Environment env;
    @Autowired
    RedissonClient redisson;

    private static final String topicKey = "redissonUserLoginTopicKey";

    public void sendLogMsg(UserLoginDto loginDto) {
        rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
        rabbitTemplate.setExchange(env.getProperty("mq.login.info.exchange.name"));
        rabbitTemplate.setRoutingKey(env.getProperty("mq.login.info.routing.key.name"));
        rabbitTemplate.convertAndSend(loginDto, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                MessageProperties properties = message.getMessageProperties();
                properties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                properties.setHeader(AbstractJavaTypeMapper.DEFAULT_CONTENT_CLASSID_FIELD_NAME, UserLoginDto.class);
                return message;
            }
        });
        LOGGER.info("生产者：{}登录成功", loginDto.getUserName());
    }

    public void sendMsg(UserLoginDto dto) {
        try {
            if (dto != null) {
                LOGGER.info("记录登录信息-生产者-发送消息：{}", dto);
                RTopic rTopic = redisson.getTopic(topicKey);
                rTopic.publishAsync(dto);
            }
        } catch (Exception e) {
            LOGGER.error("记录登录信息-生产者-异常：{}", dto, e.fillInStackTrace());
        }
    }
}
